#!/usr/bin/python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
"""Cruise Control for AppEngine test runner.

This module is responsible for patching import paths, compiling and running all
of Cruise Control for AppEngine's tests.
"""
# Python
import os
import sys
import unittest

ROOT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
SYSTEM_PATH_LIST = os.environ['PATH'].split(os.pathsep)

# Determine the AppEngine install directory
APPENGINE_DIR = None
DEV_APPSERVER_PY = 'dev_appserver.py'
for path in SYSTEM_PATH_LIST:
    dev_appserver_path = path + os.sep + DEV_APPSERVER_PY
    if os.path.exists(dev_appserver_path):
        full_path = os.path.realpath(dev_appserver_path)  # Follow Symlink
        APPENGINE_DIR = full_path.replace(DEV_APPSERVER_PY, '')

# We must have the dev_appserver install directory before we can continue
assert APPENGINE_DIR

REQUIRED_APPENGINE_PATHS = [
    APPENGINE_DIR,
    os.path.join(APPENGINE_DIR, 'google', 'appengine', 'tools'),
    os.path.join(APPENGINE_DIR, 'lib', 'antlr3'),
    os.path.join(APPENGINE_DIR, 'lib', 'django'),
    os.path.join(APPENGINE_DIR, 'lib', 'webob'),
    os.path.join(APPENGINE_DIR, 'lib', 'yaml', 'lib'),
]

# Fix the sys.path to include our required AppEngine paths.
sys.path = REQUIRED_APPENGINE_PATHS + sys.path

try:
    # New tests modules need to be imported here.
    import app_test
except ImportError:
    print "Unable to import Cruise Control for AppEngine modules."

def main():
    """Kicks off Cruise Control for AppEngine's tests.
    
    All tests should be registered here.
    """
    app_suite = unittest.TestLoader().loadTestsFromTestCase(app_test.AppTest)
    all_suites = unittest.TestSuite([app_suite])    
    unittest.TextTestRunner().run(all_suites)

if __name__ == "__main__":
    main()